package cn.com.hhrcw.web;

import cn.com.hhrcw.entity.File;
import cn.com.hhrcw.entity.LeavingNews;
import cn.com.hhrcw.entity.PiInfo;
import cn.com.hhrcw.entity.SysUser;
import cn.com.hhrcw.mapstruct.LeavingNewsConvert;
import cn.com.hhrcw.params.LeavingNewsParams;
import cn.com.hhrcw.service.IFileService;
import cn.com.hhrcw.service.ILeavingNewsService;
import cn.com.hhrcw.service.IPiInfoService;
import cn.com.hhrcw.utils.SubjectUtils;
import cn.com.hhrcw.vo.LeavingNewsVO;
import cn.com.hhrcw.vo.LeveingNewsListVO;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.base.entity.AttributesValueParams;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.function.Function;

/**
 * 留言
 *
 * @author jiangdong
 * @since 2020-11-23
 */
@RestController
@Slf4j
@RequestMapping("/personal/v1/leavingNews")
@Api(tags = "留言表")
@Validated
public class LeavingNewsController extends JeecgController<cn.com.hhrcw.entity.LeavingNews, ILeavingNewsService> {

    @Autowired
    private ILeavingNewsService leavingNewsService;

    @Autowired
    private LeavingNewsConvert leavingNewsConvert;

    @Autowired
    private IPiInfoService piInfoService;

    @Autowired
    private IFileService fileService;

    /**
     * 获取未读留言数量
     *
     * @return
     */
    @GetMapping("/getNotReadCount")
    public Result<Integer> getCount() {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        int count = service.lambdaQuery().eq(LeavingNews::getDelFlag, false).eq(LeavingNews::getReceiveId, sysUser.getId())
                .eq(LeavingNews::getReadFlag, 1).count();
        return Result.ok(count);
    }

    /**
     * 分页列表查询
     *
     * @param params 请求参数
     * @return
     */
    @GetMapping(value = "/list")
    @AutoLog("留言表-分页列表查询")
    @ApiOperation(value = "分页列表查询", notes = "分页列表查询")
    public Result<Page<LeveingNewsListVO>> list(LeavingNewsParams params, HttpServletRequest request) {
        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        LambdaQueryWrapper<LeavingNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LeavingNews::getDelFlag, false).eq(LeavingNews::getSendId, sysUser.getId())
                .isNull(LeavingNews::getPartentId);
        IPage<LeavingNews> page = leavingNewsService.page(params.page(), lambdaQueryWrapper);
        //分页结果转换器
        Function<LeavingNews, LeveingNewsListVO> fun = leavingNews -> {
            LeveingNewsListVO vo = new LeveingNewsListVO();
            LeavingNewsVO level = leavingNewsConvert.toVO(leavingNews);
            PiInfo piInfo = piInfoService.lambdaQuery().eq(PiInfo::getUserId,leavingNews.getSendId())
                    .eq(PiInfo::getDelFlag,false).one();
            if (StrUtil.isNotBlank(piInfo.getPhotoId())){
                File file = fileService.getById(piInfo.getPhotoId());
                if (file != null) {
                    level.setPhotoUrl(file.getUrl());
                }
            }

            vo.setLevel(level);
            List<LeavingNews> response = leavingNewsService.lambdaQuery()
                    .eq(LeavingNews::getDelFlag, false)
                    .eq(LeavingNews::getReceiveId, sysUser.getId())
                    .eq(LeavingNews::getPartentId, leavingNews.getId()).list();
            if (!CollectionUtils.isEmpty(response)) {
                vo.setResponse(leavingNewsConvert.toVO(response.get(0)));
            }
            return vo;
        };
        return Result.ok((Page) page.convert(fun));
    }

    /**
     * 根据id查询
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/queryById")
    @ApiOperation(value = "根据id查询", notes = "根据id查询")
    @PermissionData
    public Result<LeavingNewsVO> queryById(String id) {
        LeavingNews leavingNews = leavingNewsService
                .lambdaQuery()
                .eq(LeavingNews::getId, id)
                .eq(LeavingNews::getDelFlag, false)
                .one();
        if (leavingNews == null) {
            throw new JeecgBootException("数据不存在");
        }
        return Result.ok(leavingNewsConvert.toVO(leavingNews));
    }

    /**
     * 留言
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/add")
    @AutoLog("留言表-添加")
    @ApiOperation(value = "添加", notes = "添加")
    public Result<?> add(@RequestBody @Valid LeavingNewsParams params) {

        SysUser sysUser = (SysUser) SubjectUtils.getSubject();
        LeavingNews leavingNews = leavingNewsConvert.toEntity(params);
        leavingNews.setCreateBy(sysUser.getId());
        leavingNews.setCreateTime(DateUtil.date());
        leavingNews.setDelFlag(false);
        leavingNews.setReadFlag(1);
        //leavingNews.setNo(super.sort("leaving_news", Constant.NO_SEED));//FIXME: 编号,可根据情况隐藏
        boolean saved = leavingNewsService.save(leavingNews);
        return saved ? Result.ok() : Result.error("添加失败");
    }

    /**
     * 编辑
     *
     * @param params 请求参数
     * @return
     */
    @PostMapping(value = "/edit")
    @AutoLog("留言表-编辑")
    @ApiOperation(value = "编辑", notes = "编辑")
    public Result<?> edit(@RequestBody @Valid LeavingNewsParams params) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        LeavingNews leavingNews = leavingNewsConvert.toEntity(params);
        leavingNews.setUpdateBy(sysUser.getId());
        leavingNews.setUpdateTime(DateUtil.date());

        boolean updated = leavingNewsService.updateById(leavingNews);
        return updated ? Result.ok() : Result.error("编辑失败");
    }


    /**
     * 批量删除
     *
     * @param id 数据id
     * @return
     */
    @GetMapping(value = "/delete")
    @AutoLog("留言表-批量删除")
    @ApiOperation(value = "批量删除", notes = "批量删除")
    @RequiresPermissions("leavingNews:delete")
    public Result delete(String[] id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaUpdateWrapper<LeavingNews> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.in(cn.com.hhrcw.entity.LeavingNews::getId, id)
                .set(LeavingNews::getDelFlag, true)
                .set(LeavingNews::getUpdateBy, sysUser.getUsername())
                .set(LeavingNews::getUpdateTime, DateUtil.date());

        boolean deleted = leavingNewsService.update(updateWrapper);
        return deleted ? Result.ok() : Result.error("删除失败");
    }

    /**
     * 属性值是否重复
     *
     * @return
     */
    @Override
    @GetMapping("/propertyRepeat")
    @ApiOperation(value = "属性值是否重复", notes = "属性值是否重复")
    public Result propertyIsRepeat(@Valid AttributesValueParams params) {
        return super.propertyIsRepeat(params);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param params
     */
    @SneakyThrows
    @GetMapping(value = "/exportXls")
    @ApiOperation(value = "导出excel", notes = "导出excel")
    public Result exportXls(HttpServletRequest request, LeavingNewsParams params) {
        LeavingNews leavingNews = leavingNewsConvert.toEntity(params);
        leavingNews.setDelFlag(false);
        QueryWrapper<LeavingNews> queryWrapper = QueryGenerator.initQueryWrapper(leavingNews, request.getParameterMap());
        List<LeavingNews> data = leavingNewsService.list(queryWrapper);
        ExportParams exportParams = new ExportParams("留言表", "留言表");
        String url = super.exportXls(exportParams, LeavingNewsVO.class, leavingNewsConvert.toVO(data));
        return Result.ok((Object) url);
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @PostMapping(value = "/importExcel")
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入数据")
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, LeavingNews.class);
    }

}
